package com.chivan.encoder;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chivan.encoder.log.Logcat;
import com.chivan.encoder.recorder.BaseAudioRecorder;
import com.chivan.encoder.recorder.Constant;
import com.chivan.encoder.recorder.QTAudioRecorder;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class RecordActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "PCMSample";
    //是否在录制
    private boolean isRecording = false;
    //开始录音
    private Button startAudio;
    //结束录音
    private Button stopAudio;
    //播放录音
    private Button playAudio;
    //删除文件
    private Button deleteAudio;
    private ScrollView mScrollView;
    private TextView tv_audio_succeess;
    //pcm文件
    private File file, pcmFile;
    private BaseAudioRecorder mAudioRecorder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        initView();
        initRecorder();
    }

    private void initRecorder() {
        mAudioRecorder = new QTAudioRecorder(RecordActivity.this);
        mAudioRecorder.setDataEncoder(Constant.RecorderAudioFormat.mp3);
        mAudioRecorder.setFileEncoder(Constant.RecorderAudioFormat.mp3);
    }

    //初始化View
    private void initView() {
        mScrollView = findViewById(R.id.mScrollView);
        tv_audio_succeess = findViewById(R.id.tv_audio_succeess);
        printLog("初始化成功");
        startAudio = findViewById(R.id.startAudio);
        startAudio.setOnClickListener(this);
        stopAudio = findViewById(R.id.stopAudio);
        stopAudio.setOnClickListener(this);
        playAudio = findViewById(R.id.playAudio);
        playAudio.setOnClickListener(this);
        deleteAudio = findViewById(R.id.deleteAudio);
        deleteAudio.setOnClickListener(this);
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startAudio:
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        StartRecord();
                        Log.e(TAG, "start");
                    }
                });
                thread.start();
                printLog("开始录音");
                ButtonEnabled(false, true, false);
                break;
            case R.id.stopAudio:
                isRecording = false;
                ButtonEnabled(true, false, true);
                stopRecord();
                printLog("停止录音");
//                printLog("pcm: " + file.getPath());
                break;
            case R.id.playAudio:
                Log.i(TAG, "开始播放");
//                PlayRecord();
                playMp3();
                ButtonEnabled(true, false, false);
                break;
            case R.id.deleteAudio:
                deleFile();
                break;
        }
    }

    //打印log
    private void printLog(final String resultString) {
        tv_audio_succeess.post(new Runnable() {
            @Override
            public void run() {
                tv_audio_succeess.append(resultString + "\n");
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    //获取/失去焦点
    private void ButtonEnabled(boolean start, boolean stop, boolean play) {
        startAudio.setEnabled(true);
        stopAudio.setEnabled(true);
        playAudio.setEnabled(true);
    }

    //开始录音
    public void StartRecord() {
        if (mAudioRecorder != null) {
//            mAudioRecorder.setMaxDuration(maximumDuration);
//            mAudioRecorder.setAudioFilePath(audioFilePath);
            mAudioRecorder.startRecording();
        }
    }

    private void stopRecord() {
        if (mAudioRecorder != null) {
            mAudioRecorder.stopRecording();
        }
    }

    public static byte[] changeBytes(byte[] a) {
        byte[] b = new byte[a.length];
        for (int i = 0; i < b.length; i++) {
            b[i] = a[b.length - i - 1];
        }
        return b;
    }

    //播放文件
    public void PlayRecord() {
        Log.i(TAG, "play pcm");
//        String pcmPath = "/storage/emulated/0/test_pcm.pcm";//pcm文件路径，文件要存在！
//        file = new File(pcmPath);
        if (pcmFile == null) {
//            return;
            pcmFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/qt_record_file-1.pcm");
        }
//        playMp3();
        //读取文件
        int musicLength = (int) (pcmFile.length() / 2);
        short[] music = new short[musicLength];
        try {
            InputStream is = new FileInputStream(pcmFile);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);
            int i = 0;
            while (dis.available() > 0) {
                music[i] = dis.readShort();
                i++;
            }
            dis.close();
            AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    16000, AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    musicLength * 2,
                    AudioTrack.MODE_STREAM);
            audioTrack.play();
            audioTrack.write(music, 0, musicLength);
            audioTrack.stop();
        } catch (Throwable t) {
            Log.e(TAG, "播放失败");
        }
    }


    public void playMp3() {
        String mp3Path = "";
        if (mAudioRecorder != null) {
            mp3Path = mAudioRecorder.getDefaultMp3Path();
        }
        try {
            if (!mp3Path.isEmpty()) {
                File file = new File(mp3Path);
                if (!file.exists()) {
                    Logcat.i("播放文件不存在：" + mp3Path);
                    return;
                }
            }
            Logcat.i("播放文件：" + mp3Path);
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(mp3Path);
            mp.prepare();
            mp.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除文件
    private void deleFile() {
        if (file == null) {
            return;
        }
        file.delete();
        printLog("文件删除成功");
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopRecord();
    }
}
